import { NextFunction, Request, Response } from "express";
import useragent from "useragent"; // 解析 User-Agent
import requestIp from "request-ip"; // 解析 IP 地
import { getUserMes } from "../Db/redis";
import { decryptObject } from "../utils";

// 中间件函数
//校验session
export const sessionValidator = async (
  req: any,
  res: any,
  next: NextFunction
) => {
  const cookies = req.headers.cookie;
  const Authorization = req.headers.authorization;
  if (!cookies && !Authorization) {
    return res.status(200).json({
      code: 401,
      message: "未登录或登陆过期",
    });
  }
  const List = cookies
    ? cookies.split("storeIt=")
    : Authorization.split("storeIt=");
  if (List.length < 2)
    return res.status(200).json({
      code: 401,
      message: "未登录或登陆过期",
    });
  const str = List[1];
  const mes = decryptObject(str);
  if (!mes || !mes.accountId || !mes.email) {
    return res.status(200).json({
      code: 401,
      message: "未登录或登陆过期",
    });
  }
  // 获取当前时间（单位：秒）
  const currentTime = Math.floor(Date.now() / 1000);

  // 比较当前时间和JWT中的exp字段
  if (mes.exp && currentTime > mes.exp) {
    return res.status(200).json({
      code: 401,
      message: "未登录或登陆过期",
    }); // 如果当前时间大于过期时间，则表示过期
  }
  // 继续处理后续的请求
  req.accountId = mes.accountId;
  req.email = mes.email;
  next();
};

export const getIp = (req: any, res: any, next: NextFunction) => {
  const ip = requestIp.getClientIp(req) || req.ip || "";
  const agent = useragent.parse(req.headers["user-agent"] || "");
  const deviceInfo = {
    browser: agent.family, // 浏览器
    os: agent.os.family, // 操作系统
    device: agent.device.family || "未知设备", // 设备类型
  };
  const userIp =
    "\n" +
    ip +
    "---" +
    deviceInfo.browser +
    "---" +
    deviceInfo.os +
    "---" +
    deviceInfo.device +
    "---";
  req.userIp = userIp;
  next();
};
